import i18n from '@/i18n'
import { FlowFileDao } from '@apps/flow/domain/flow-file/flow-file.dao'
import { DomainModel } from '@apps/flow/domain/model'
import { Assist } from '@libs/lhy-common'
import { Body, Controller, Delete, Get, Post, Put, Query } from '@nestjs/common'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { FlowFileBatchSaveDto } from './dto/flow-file-batch-save.dto'
import { FlowFileListGroupDto } from './dto/flow-file-list-group.dto'
import { FlowFileSaveDto } from './dto/flow-file-save.dto'
import { FlowFileTreeDto } from './dto/flow-File-tree.dto'
import { FlowFileUpdateDto } from './dto/flow-file-update.dto'
import { FlowFileService } from './flow-file.service'

@ApiTags('文件')
@Controller({ path: 'file', version: '1' })
export class FlowFileController {
  constructor(
    private fileDao: FlowFileDao,
    private fileService: FlowFileService
  ) {}

  @ApiOperation({ summary: '获取分组列表' })
  @Get('list_group')
  async listGroup(@Query() param: FlowFileListGroupDto) {
    return this.fileDao.listGroup(param)
  }

  @ApiOperation({ summary: '获取文件树结构' })
  @Get('tree')
  async tree(@Query() param: FlowFileTreeDto) {
    return this.fileService.tree(param)
  }

  @ApiOperation({ summary: '新增文件' })
  @Put('save')
  async save(@Body() param: FlowFileSaveDto) {
    Assist.threw(await this.fileDao.isLabelExists([param]), `文件名称${param.label}已存在`)

    await this.fileDao.save({
      ...param,
      belong: DomainModel.FlowFileBelong.Platform,
    })
  }

  @ApiOperation({ summary: '批量新增/更新文件' })
  @Put('batch_save')
  async batchSave(@Body() param: FlowFileBatchSaveDto) {
    if (param.cover) {
      await this.fileDao.batchUpsertOnUnique(param.files, DomainModel.FlowFileBelong.Platform)
    } else {
      Assist.threw(
        await this.fileDao.isLabelExists(
          param.files.map(file => ({
            platform: file.platform,
            groupLabel: file.groupLabel,
            label: file.label,
          }))
        ),
        '存在同名文件名称，导入失败'
      )

      await this.fileDao.batchSave(
        param.files.map(file => ({
          ...file,
          belong: DomainModel.FlowFileBelong.Platform,
        }))
      )
    }
  }

  @ApiOperation({ summary: '更新文件' })
  @Post('update')
  async update(@Body() param: FlowFileUpdateDto) {
    const oldData = Assist.notNull(await this.fileDao.getById(param.id), `文件[id=${param.id}]不存在`)
    Assist.threw(oldData.belong === DomainModel.FlowFileBelong.System, '系统文件不允许修改')
    Assist.threw(
      await this.fileDao.isLabelExists([{ ...param, platform: oldData.platform }]),
      `文件名称[${param.label}]已存在`
    )

    await this.fileDao.updateById(param.id, param)
  }

  @ApiOperation({ summary: '根据ID删除文件' })
  @Delete('del')
  async del(@Query('id') id: number) {
    const oldData = Assist.notNull(await this.fileDao.getById(id), `文件[id=${id}]不存在`)
    Assist.threw(oldData.belong === DomainModel.FlowFileBelong.System, '系统文件不允许删除')

    await this.fileDao.deleteById(id)
  }
}
